package com.i2works.smartluolong.web.controller.user;


import com.google.common.collect.Lists;
import com.i2works.smartluolong.utils.base.DateConstant;
import com.i2works.smartluolong.utils.base.MsgEnum;
import com.i2works.smartluolong.utils.common.DateUtils;
import com.i2works.smartluolong.utils.common.SmsUtil;
import com.i2works.smartluolong.utils.common.WebUtil;
import com.i2works.smartluolong.utils.entity.R;
import com.i2works.smartluolong.utils.entity.Result;
import com.i2works.smartluolong.utils.exception.ServiceException;
import com.i2works.smartluolong.web.entity.cart.CartReceiveDO;
import com.i2works.smartluolong.web.entity.cart.CartReceiveQuery;
import com.i2works.smartluolong.web.entity.court.*;
import com.i2works.smartluolong.web.entity.user.UserAccountDO;
import com.i2works.smartluolong.web.entity.user.UserAccountQuery;
import com.i2works.smartluolong.web.entity.user.UserLoginVO;
import com.i2works.smartluolong.web.service.cart.ICartReceiveService;
import com.i2works.smartluolong.web.service.court.*;
import com.i2works.smartluolong.web.service.user.IUserAccountService;
import com.i2works.smartluolong.web.utils.BaseModule;
import com.xiaoleilu.hutool.util.CollectionUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;


/**
 * 会员中心（基础资料）
 *
 * @author koal <koal@vip.qq.com>
 * @date 2017/10/19 10:40
 */
@Controller
@RequestMapping("/user")
public class UserBasicController extends BaseModule {

    private final IUserAccountService userAccountService;

    private final SmsUtil smsUtil;

    private final ICartReceiveService cartReceiveService;

    private final ICourtLawsuitService lawsuitService;

    private final ICourtOtherService otherService;

    private final ICourtHouseService houseService;

    private final ICourtSuggestService suggestService;

    private final ICourtAssetService courtAssetService;

    private final ICourtRelativesService receiveService;

    private final ICourtCarService  carService;


    @Autowired
    public UserBasicController(IUserAccountService userAccountService, SmsUtil smsUtil, ICartReceiveService cartReceiveService,
                               ICourtLawsuitService lawsuitService,ICourtOtherService otherService,
                               ICourtHouseService houseService,ICourtSuggestService suggestService,
                               ICourtAssetService courtAssetService,ICourtRelativesService receiveService,ICourtCarService  carService) {
        this.userAccountService = userAccountService;
        this.smsUtil = smsUtil;
        this.cartReceiveService = cartReceiveService;
        this.lawsuitService=lawsuitService;
        this.carService=carService;
        this.suggestService=suggestService;
        this.receiveService=receiveService;
        this.courtAssetService=courtAssetService;
        this.houseService=houseService;
        this.otherService=otherService;
    }

    /**
     * 会员中心主页页面
     */
    @GetMapping("/index")
    public String index(Model model) {
        try {
            model.addAttribute("time", DateUtils.get(DateConstant.YYYY_MM_DD));
            //婚姻诉讼
            CourtLawsuitQuery lawsuitQuery=new CourtLawsuitQuery();
            lawsuitQuery.setUserId(getUserId());
            lawsuitQuery.setState(1);
            Integer lawsuitCount=lawsuitService.queryCount(lawsuitQuery);
            model.addAttribute("lawsuitCount",lawsuitCount);
        } catch (Exception e) {
            logger.error("会员中心主页页面异常：" + e.getMessage());
        }
        return "/user/index";
    }
    /**
     * 查看诉讼详情
     */
    @RequestMapping("/details")
    public String details(Integer lawsuitId,String site, Model model) {
        CourtLawsuitQuery courtLawsuitQuery = new CourtLawsuitQuery();
        try {
            courtLawsuitQuery.setId(lawsuitId);
            CourtLawsuitDO courtLawsuitDO = lawsuitService.query(courtLawsuitQuery);
            //获取财产信息
            if (courtLawsuitDO.getHaveAsset() == 0) {
                model.addAttribute("asset", null);
            } else {
                CourtAssetQuery courtAssetQuery = new CourtAssetQuery();
                courtAssetQuery.setLawsuitId(lawsuitId);
                List<CourtAssetDO> courtAssetDOList = courtAssetService.queryList(courtAssetQuery);
                model.addAttribute("asset", courtAssetDOList);
            }
            //获取子女信息
            if (courtLawsuitDO.getHaveSon() == 0) {
                model.addAttribute("son", null);
            } else {
                CourtRelativesQuery relativesQuery = new CourtRelativesQuery();
                relativesQuery.setLawsuitId(lawsuitId);
                List<CourtRelativesDO> courtRelativesDOS = receiveService.queryList(relativesQuery);
                model.addAttribute("son", courtRelativesDOS);
            }
            //获取车辆信息
            if (courtLawsuitDO.getHaveCar() == 0) {
                model.addAttribute("car", null);
            } else {
                CourtCarQuery carQuery = new CourtCarQuery();
                carQuery.setLawsuitId(lawsuitId);
                List<CourtCarDO> carDOS = carService.queryList(carQuery);
                model.addAttribute("car", carDOS);
            }
            //获取房产信息
            if (courtLawsuitDO.getHaveHouse() == 0) {
                model.addAttribute("house", null);
            } else {
                CourtHouseQuery houseQuery = new CourtHouseQuery();
                houseQuery.setLawsuitId(lawsuitId);
                List<CourtHouseDO> houseDOS = houseService.queryList(houseQuery);
                model.addAttribute("house", houseDOS);
            }
            //其他财产
            CourtOtherQuery courtOtherQuery = new CourtOtherQuery();
            courtOtherQuery.setLawsuitId(lawsuitId);
            int otherCount = otherService.queryCount(courtOtherQuery);
            if (otherCount > 0) {
                List<CourtOtherDO> otherDOS = otherService.queryList(courtOtherQuery);
                model.addAttribute("other", otherDOS);
            } else {
                model.addAttribute("other", null);
            }
            //审批日志
            CourtSuggestQuery suggestQuery = new CourtSuggestQuery();
            suggestQuery.setLawsuitId(lawsuitId);
            int suggestCount = suggestService.queryCount(suggestQuery);
            if (suggestCount > 0) {
                List<CourtSuggestDO> suggestDOS = suggestService.queryList(suggestQuery);
                model.addAttribute("suggest", suggestDOS);
            } else {
                model.addAttribute("suggest", null);
            }
            //申报信息
            CourtLawsuitQuery lawsuitQuery = new CourtLawsuitQuery();
            lawsuitQuery.setId(lawsuitId);
            int lawsuitCount = lawsuitService.queryCount(lawsuitQuery);
            if (lawsuitCount > 0) {
                List<CourtLawsuitDO> lawsuitDOS = lawsuitService.queryList(lawsuitQuery);
                model.addAttribute("lawsuit", lawsuitDOS);
            } else {
                model.addAttribute("lawsuit", null);
            }
        } catch (Exception e) {
            logger.error("查看会员中心诉讼详情出错:" + e.getMessage());
        }
        return "/user/details";
    }

    /**
     * 搜索
     */
    @RequestMapping("/search")
    @ResponseBody
    public Result search(CourtLawsuitQuery courtLawsuitQuery) {

        try {
            if(StringUtils.isEmpty(courtLawsuitQuery.getPlaintiffCardNumber())){
               courtLawsuitQuery.setPlaintiffCardNumber(null);
            }
            Integer queryCount = lawsuitService.queryCount(courtLawsuitQuery);
            List<CourtLawsuitDO> courtLawsuitDOS = lawsuitService.queryList(courtLawsuitQuery);
            return R.success(courtLawsuitDOS,queryCount);
        } catch (Exception e) {
            logger.error("查询出错" + e.getMessage());
            return R.error("会员中心搜索婚姻事项出错");
        }
    }
    /**
     * 用户办件
     */
    @GetMapping("/transact")
    public String transact(Model model) {
        return "/user/transact";
    }
    
    /**
     * 一窗多办
     */
    @GetMapping("/windowOffices")
    public String windowOffices(Model model) {
        return "/user/windowOffices";
    }

    /**
     * 证件领取
     */
    @GetMapping("/receive")
    public String receive(Model model) {
        return "/user/receive";
    }
    
    
    /**
     * 一窗多办
     */
    @GetMapping("/suggestion")
    public String suggestion(Model model) {
        return "/user/suggestion";
    }

    /**
     * 证件领取
     */
    @GetMapping("/receive/api")
    @ResponseBody
    public Result receiveApi(@ModelAttribute CartReceiveQuery cartReceiveQuery) {
        List<CartReceiveDO> resultList = Lists.newArrayList();
        try {
            cartReceiveQuery.setIssueStatus(1);
            cartReceiveQuery.setItemUserId(getUserId());
            Integer count = cartReceiveService.queryCount(cartReceiveQuery);
            if (count > 0) {
                List<CartReceiveDO> queryList = cartReceiveService.queryList(cartReceiveQuery);
                if (CollectionUtil.isNotEmpty(queryList)) {
                    for (CartReceiveDO cartReceiveDO : queryList) {
                        String typeValue = WebUtil.itemTypeValue(cartReceiveDO.getItemType());
                        cartReceiveDO.setItemTypeValue(typeValue);
                        resultList.add(cartReceiveDO);
                    }
                }
            }
            return R.success(resultList, count);
        } catch (ServiceException e) {
            logger.error("", e.getMessage());
            return R.error(MsgEnum.SYSTEM_ERROR.getMsg());
        }
    }

    /**
     * 用户设置页面
     */
    @GetMapping("/settings")
    public String settings(Model model) {
        model.addAttribute("user", getLoginUser());
        return "/user/settings";
    }


    /**
     * 账号信息页面
     */
    @GetMapping("/info")
    public String info(Model model) {
        return "/user/info";
    }

    /**
     * 投诉建议页面
     */
    @GetMapping("/suggest")
    public String suggest(Model model) {
        return "/user/suggest";
    }

    /**
     * 修改密码页面
     */
    @GetMapping("/password")
    public String passwordPage(Model model) {
        return "/user/password";
    }

    /**
     * 修改密码方法
     */
    @PostMapping("/password/save")
    @ResponseBody
    public Result password(@ModelAttribute UserLoginVO userLoginVO) {
        //实体
        if (null == userLoginVO) {
            return R.error(MsgEnum.ATTRS_EMPTY.getMsg());
        }

        //判断手机号密码是否为空
        if (StringUtils.isAnyBlank(userLoginVO.getPhone(), userLoginVO.getPassword())) {
            return R.error(MsgEnum.ACCESS_PHOMEPASSWORD_EMPTY.getMsg());
        }

//        //短信验证码
//        Result result = checkSmsCode(userLoginVO.getPhone(), userLoginVO.getCode());
//        if (!result.getSuccess()) {
//            return result;
//        }

        try {
            //判断账号是否存在
            UserAccountQuery userAccountQuery = new UserAccountQuery();
            userAccountQuery.setPhone(userLoginVO.getPhone());
            int queryCheck = userAccountService.queryCheck(userAccountQuery);
            if (queryCheck > 0) {
                UserAccountDO userAccountDO = new UserAccountDO();
                userAccountDO.setPhone(userLoginVO.getPhone());
                userAccountDO.setPassword(userLoginVO.getPassword());
                userAccountService.updatePassword(userAccountDO);
                Session session_old  =SecurityUtils.getSubject().getSession();
                Integer 	 adminUserId=(Integer) session_old.getAttribute("adminUserId");
                String   	 adminUserName= (String) session_old.getAttribute("adminUserName");
                //退出登录
                SecurityUtils.getSubject().logout();
                //传递给新session
                Session session_new  =SecurityUtils.getSubject().getSession();
                session_new.setAttribute("windowOffices", "windowOffices");
                session_new.setAttribute("adminUserId", adminUserId);
                session_new.setAttribute("adminUserName", adminUserName);
                return R.success(MsgEnum.ACCESS_UPDATE_PASSWORD_SUCCESS.getMsg());
            } else {
                return R.error(MsgEnum.ACCESS_PHONE_NOKNOW.getMsg());
            }
        } catch (ServiceException e) {
            logger.error("登录异常：" + e.getMessage());
            return R.error(MsgEnum.ACCESS_UPDATE_PASSWORD_FAIL.getMsg());
        }
    }


    /**
     * 判断短信验证码
     *
     * @param phone 手机号
     * @param code  验证码
     */
    private Result checkSmsCode(String phone, String code) {
        if (StringUtils.isBlank(code)) {
            return R.error(MsgEnum.SMS_CODE_EMPTY.getMsg());
        } else {
            //判断验证码是否正确
            Result contrast = smsUtil.contrast(phone, code);
            //对比失败返回
            if (!contrast.getSuccess()) {
                return contrast;
            } else {
                //删除缓存
                smsUtil.delete(phone);
            }
            return R.success();
        }
    }

}